package com.zhaoxi.project.hrp.service;

import com.zhaoxi.common.constant.CacheConstants;
import com.zhaoxi.common.constant.Constants;
import com.zhaoxi.common.constant.UserConstants;
import com.zhaoxi.common.exception.ServiceException;
import com.zhaoxi.common.exception.user.CaptchaException;
import com.zhaoxi.common.exception.user.CaptchaExpireException;
import com.zhaoxi.common.utils.MessageUtils;
import com.zhaoxi.common.utils.SecurityUtils;
import com.zhaoxi.common.utils.StringUtils;
import com.zhaoxi.common.utils.bean.BeanValidators;
import com.zhaoxi.common.utils.spring.SpringUtils;
import com.zhaoxi.framework.manager.AsyncManager;
import com.zhaoxi.framework.manager.factory.AsyncFactory;
import com.zhaoxi.framework.redis.RedisCache;
import com.zhaoxi.framework.security.LoginBody;
import com.zhaoxi.framework.web.BaseService;
import com.zhaoxi.framework.web.PageData;
import com.zhaoxi.project.hrp.domain.*;
import com.zhaoxi.project.hrp.mapper.*;
import com.zhaoxi.project.sys.service.impl.SysConfigServiceImpl;
import jakarta.validation.Validator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户 业务层处理
 *
 * @author zhaoxi
 */
@Service
public class UserService extends BaseService {
  private static final Logger log = LoggerFactory.getLogger(UserService.class);

  @Autowired
  private SysUserMapper userMapper;

  @Autowired
  private SysRoleMapper roleMapper;

  @Autowired
  private HrpPostMapper postMapper;

  @Autowired
  private SysUserRoleMapper userRoleMapper;

  @Autowired
  private SysUserPostMapper userPostMapper;

  @Autowired
  private SysConfigServiceImpl configService;

  @Autowired
  private RedisCache redisCache;

  @Autowired
  protected Validator validator;


  //查询数据集合
  public List<PageData> getList(PageData pd) {
    return userMapper.getList(pd);
  }

  //查询数据对象 通过id
  public PageData getById(PageData pd) {
    PageData pd1 = new PageData();
    if (pd.getLong("id") == null) {
      return null;
    }
    pd1.put("id", pd.getLong("id"));
    List<PageData> list = userMapper.getList(pd1);
    if (list.size() > 0) {
      return list.get(0);
    }
    return null;
  }

  //查询数据对象 通过id
  public int checkUserUnique(PageData pd) {
    String userId = pd.getString("userId");
    pd.put("userId",null);
    List<PageData> list = userMapper.getList(pd);
    int i = 0;
    for (PageData k : list){
      if (! k.getString("userId").equals(userId)){
        i ++;
      }
    }
    return i;
  }

  //新增
  public PageData addUser(PageData pd) {
    return this.responses(userMapper.add(pd));
  }

  //更新
  public PageData edit(PageData pd) {
    return this.responses(userMapper.edit(pd));
  }

  @Transactional(propagation = Propagation.REQUIRED)
  public PageData editLoginName(PageData pd) {
    PageData res = this.checkUserLoginNamePwd(pd);
    if (res.isError() ){
      return res;
    }
    pd.put("password", SecurityUtils.encryptPassword(pd.getString("password")));
    pd.put("isSys","0");
    return this.responses(userMapper.editLoginName(pd));
  }

  //删除
  public PageData del(Long id) {
    return this.responses(userMapper.del(id));
  }


  /**
   * 注册
   */
  @Transactional(propagation = Propagation.REQUIRED)
  public PageData register(LoginBody registerBody) {
    String msg = "", loginName = registerBody.getLoginName(), password = registerBody.getPassword();

    // 验证码开关
    boolean captchaEnabled = configService.selectCaptchaEnabled();
    if (captchaEnabled) {
      validateCaptcha(loginName, registerBody.getCode(), registerBody.getUuid());
    }

    PageData params = new PageData();
    params.put("loginName",loginName);
    params.put("status","0");//状态要给0
    userMapper.add(params);//新增
    if (params.isEmpty("user_id")){
      msg = "注册失败,请联系系统管理人员";
      TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      return this.error(msg);
    }
    params.put("tenantId",params.getLong("user_id"));
    params.put("userId",params.getLong("user_id"));
    if (userMapper.editTenantId(params) < 1) {//租户号更新
      msg = "注册失败,请联系系统管理人员";
      TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      return this.error(msg);
    }

    params.put("password",password);
    PageData res = this.editLoginName(params);//账户号密码更新
    if (res.isError()){
      return res;
    }

    params.put("roleId",2);//要给固定的租户管理员的权限码
    userMapper.addRole(params);
    if (res.isError()){
      return res;
    }
    AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginName, Constants.REGISTER, MessageUtils.message("user.register.success")));
    return res;
  }

  public PageData checkUserLoginNamePwd(PageData pd){
    String msg = "", loginName = pd.getString("loginName"), password = pd.getString("password");

    if (pd.isEmpty("loginName")) {
      msg = "用户名不能为空";
      return this.error(msg);
    } else if (pd.isEmpty("password")) {
      msg = "用户密码不能为空";
      return this.error(msg);
    } else if (loginName.length() < UserConstants.USERNAME_MIN_LENGTH
        || loginName.length() > UserConstants.USERNAME_MAX_LENGTH) {
      msg = "账户长度必须在2到20个字符之间";
      return this.error(msg);
    } else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
        || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
      msg = "密码长度必须在5到20个字符之间";
      return this.error(msg);
    }
    PageData params = new PageData();
    params.put("loginName",loginName);
    if (this.checkUserUnique(params) > 0) {
      msg = "用户账号：'" + loginName + "'失败，注册账号已存在";
      return this.error(msg);
    }
    return this.success();
  }
  /**
   * 校验验证码
   *
   * @param userName 用户名
   * @param code     验证码
   * @param uuid     唯一标识
   * @return 结果
   */
  public void validateCaptcha(String userName, String code, String uuid) {
    String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
    String captcha = redisCache.getCacheObject(verifyKey);
    redisCache.deleteObject(verifyKey);
    if (captcha == null) {
      throw new CaptchaExpireException();
    }
    if (!code.equalsIgnoreCase(captcha)) {
      throw new CaptchaException();
    }
  }

//  2024年2月6日, PM 12:09:10
  //============之前的暂时不关联，以后慢慢改吧======================

  /**
   * 校验用户名称是否唯一
   *
   * @param user 用户信息
   * @return 结果
   */

  public boolean checkUserNameUnique(SysUser user) {
    Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
    SysUser info = userMapper.checkUserNameUnique(user.getLoginName());
    if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
      return UserConstants.NOT_UNIQUE;
    }
    return UserConstants.UNIQUE;
  }

  /**
   * 校验用户名称是否唯一
   *
   * @param user 用户信息
   * @return
   */

  public boolean checkPhoneUnique(SysUser user) {
    Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
    SysUser info = userMapper.checkPhoneUnique(user.getMobile());
    if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
      return UserConstants.NOT_UNIQUE;
    }
    return UserConstants.UNIQUE;
  }

  /**
   * 校验email是否唯一
   *
   * @param user 用户信息
   * @return
   */

  public boolean checkEmailUnique(SysUser user) {
    Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
    SysUser info = userMapper.checkEmailUnique(user.getEmail());
    if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
      return UserConstants.NOT_UNIQUE;
    }
    return UserConstants.UNIQUE;
  }


  /**
   * 根据条件分页查询用户列表
   *
   * @param user 用户信息
   * @return 用户信息集合信息
   */

  // @DataScope(deptAlias = "d", userAlias = "u")
  public List<SysUser> selectUserList(SysUser user) {
    //管理员查询用户去除租户id查询过滤条件（租户查询用户不去除租户id查询过滤条件）
    if (this.getTenantId() == 1) {
      user.setTenantId(null);
    } else {
      user.setTenantId(this.getTenantId());
    }
    return userMapper.selectUserList(user);
  }

  /**
   * 根据条件分页查询已分配用户角色列表
   *
   * @param user 用户信息
   * @return 用户信息集合信息
   */

  // @DataScope(deptAlias = "d", userAlias = "u")
  public List<SysUser> selectAllocatedList(SysUser user) {
    return userMapper.selectAllocatedList(user);
  }

  /**
   * 根据条件分页查询未分配用户角色列表
   *
   * @param user 用户信息
   * @return 用户信息集合信息
   */

  // @DataScope(deptAlias = "d", userAlias = "u")
  public List<SysUser> selectUnallocatedList(SysUser user) {
    return userMapper.selectUnallocatedList(user);
  }

  /**
   * 通过用户名查询用户
   *
   * @param userName 用户名
   * @return 用户对象信息
   */

  public SysUser selectUserByUserName(String userName) {
    return userMapper.selectUserByUserName(userName);
  }

  /**
   * 通过用户ID查询用户
   *
   * @param userId 用户ID
   * @return 用户对象信息
   */

  public SysUser selectUserById(Long userId) {
    return userMapper.selectUserById(userId);
  }

  /**
   * 查询用户所属角色组
   *
   * @param userName 用户名
   * @return 结果
   */

  public String selectUserRoleGroup(String userName) {
    List<SysRole> list = roleMapper.selectRolesByUserName(userName);
    if (CollectionUtils.isEmpty(list)) {
      return StringUtils.EMPTY;
    }
    return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
  }

  /**
   * 查询用户所属岗位组
   *
   * @param userName 用户名
   * @return 结果
   */

  public String selectUserPostGroup(String userName) {
    List<HrpPost> list = postMapper.selectPostsByUserName(userName);
    if (CollectionUtils.isEmpty(list)) {
      return StringUtils.EMPTY;
    }
    return list.stream().map(HrpPost::getPostName).collect(Collectors.joining(","));
  }


  /**
   * 校验用户是否允许操作
   *
   * @param user 用户信息
   */

  public void checkUserAllowed(SysUser user) {
    if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin()) {
      throw new ServiceException("不允许操作超级管理员用户");
    }
  }

  /**
   * 校验用户是否有数据权限
   *
   * @param userId 用户id
   */

  public void checkUserDataScope(Long userId) {
    if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
      SysUser user = new SysUser();
      user.setUserId(userId);
      List<SysUser> users = SpringUtils.getAopProxy(this).selectUserList(user);
      if (StringUtils.isEmpty(users)) {
        throw new ServiceException("没有权限访问用户数据！");
      }
    }
  }

  /**
   * 新增保存用户信息
   *
   * @param user 用户信息
   * @return 结果
   */

  @Transactional
  public int insertUser(SysUser user) {
    // 新增用户信息
    user.setTenantId(getTenantId());
    user.setCreateBy(getUsername());
    user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
    int rows = userMapper.insertUser(user);
    // 新增用户岗位关联
    insertUserPost(user);
    // 新增用户与角色管理
    insertUserRole(user);
    return rows;
  }

  /**
   * 修改保存用户信息
   *
   * @param user 用户信息
   * @return 结果
   */

  @Transactional
  public int updateUser(SysUser user) {
    Long userId = user.getUserId();
    // 删除用户与角色关联
    userRoleMapper.deleteUserRoleByUserId(userId);
    // 新增用户与角色管理
    insertUserRole(user);
    // 删除用户与岗位关联
    userPostMapper.deleteUserPostByUserId(userId);
    // 新增用户与岗位管理
    insertUserPost(user);
    if (user.getPassword() != null) {
      user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));// 修改用户密码时对密码加密
    }
    return userMapper.updateUser(user);
  }

  /**
   * 用户授权角色
   *
   * @param userId  用户ID
   * @param roleIds 角色组
   */

  @Transactional
  public void insertUserAuth(Long userId, Long[] roleIds) {
    userRoleMapper.deleteUserRoleByUserId(userId);
    insertUserRole(userId, roleIds);
  }

  /**
   * 修改用户状态
   *
   * @param user 用户信息
   * @return 结果
   */

  public int updateUserStatus(SysUser user) {
    return userMapper.updateUser(user);
  }

  /**
   * 修改用户基本信息
   *
   * @param user 用户信息
   * @return 结果
   */

  public int updateUserProfile(SysUser user) {
    return userMapper.updateUser(user);
  }

  /**
   * 修改用户头像
   *
   * @param userName 用户名
   * @param avatar   头像地址
   * @return 结果
   */

  public boolean updateUserAvatar(String userName, String avatar) {
    return userMapper.updateUserAvatar(userName, avatar) > 0;
  }

  /**
   * 重置用户密码
   *
   * @param user 用户信息
   * @return 结果
   */

  public int resetPwd(SysUser user) {
    return userMapper.updateUser(user);
  }

  /**
   * 重置用户密码
   *
   * @param userName 用户名
   * @param password 密码
   * @return 结果
   */

  public int resetUserPwd(String userName, String password) {
    return userMapper.resetUserPwd(userName, password);
  }

  /**
   * 新增用户角色信息
   *
   * @param user 用户对象
   */
  public void insertUserRole(SysUser user) {
    this.insertUserRole(user.getUserId(), user.getRoleIds());
  }

  /**
   * 新增用户岗位信息
   *
   * @param user 用户对象
   */
  public void insertUserPost(SysUser user) {
    Long[] posts = user.getPostIds();
    if (StringUtils.isNotEmpty(posts)) {
      // 新增用户与岗位管理
      List<SysUserPost> list = new ArrayList<SysUserPost>(posts.length);
      for (Long postId : posts) {
        SysUserPost up = new SysUserPost();
        up.setUserId(user.getUserId());
        up.setPostId(postId);
        list.add(up);
      }
      userPostMapper.batchUserPost(list);
    }
  }

  /**
   * 新增用户角色信息
   *
   * @param userId  用户ID
   * @param roleIds 角色组
   */
  public void insertUserRole(Long userId, Long[] roleIds) {
    if (StringUtils.isNotEmpty(roleIds)) {
      // 新增用户与角色管理
      List<SysUserRole> list = new ArrayList<SysUserRole>(roleIds.length);
      for (Long roleId : roleIds) {
        SysUserRole ur = new SysUserRole();
        ur.setUserId(userId);
        ur.setRoleId(roleId);
        list.add(ur);
      }
      userRoleMapper.batchUserRole(list);
    }
  }

  /**
   * 通过用户ID删除用户
   *
   * @param userId 用户ID
   * @return 结果
   */

  @Transactional
  public int deleteUserById(Long userId) {
    checkUserAllowed(new SysUser(userId));
    checkUserDataScope(userId);
    // 删除用户与角色关联
    userRoleMapper.deleteUserRoleByUserId(userId);
    // 删除用户与岗位表
    userPostMapper.deleteUserPostByUserId(userId);
    return userMapper.deleteUserById(userId);
  }

  /**
   * 将具有删除标记的用户信息彻底删除
   *
   * @param userId
   */
  public int completeDeleteUserById(Long userId) {
    return userMapper.completeDeleteUserById(userId);
  }

  /**
   * 批量删除用户信息
   *
   * @param userIds 需要删除的用户ID
   * @return 结果
   */

  @Transactional
  public int deleteUserByIds(Long[] userIds) {
    for (Long userId : userIds) {
      checkUserAllowed(new SysUser(userId));
      checkUserDataScope(userId);
    }
    // 删除用户与角色关联
    userRoleMapper.deleteUserRole(userIds);
    // 删除用户与岗位关联
    userPostMapper.deleteUserPost(userIds);
    return userMapper.deleteUserByIds(userIds);
  }

  /**
   * 导入用户数据
   *
   * @param userList        用户数据列表
   * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
   * @param operName        操作用户
   * @return 结果
   */

  public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
    if (StringUtils.isNull(userList) || userList.size() == 0) {
      throw new ServiceException("导入用户数据不能为空！");
    }
    int successNum = 0;
    int failureNum = 0;
    StringBuilder successMsg = new StringBuilder();
    StringBuilder failureMsg = new StringBuilder();
    String password = configService.selectConfigByKey("sys.user.initPassword");
    for (SysUser user : userList) {
      try {
        // 验证是否存在这个用户
        SysUser u = userMapper.selectUserByUserName(user.getLoginName());
        if (StringUtils.isNull(u)) {
          BeanValidators.validateWithException(validator, user);
          user.setPassword(SecurityUtils.encryptPassword(password));
          user.setCreateBy(operName);
          userMapper.insertUser(user);
          successNum++;
          successMsg.append("<br/>" + successNum + "、账号 " + user.getLoginName() + " 导入成功");
        } else if (isUpdateSupport) {
          BeanValidators.validateWithException(validator, user);
          checkUserAllowed(u);
          checkUserDataScope(u.getUserId());
          user.setUserId(u.getUserId());
          user.setUpdateBy(operName);
          userMapper.updateUser(user);
          successNum++;
          successMsg.append("<br/>" + successNum + "、账号 " + user.getLoginName() + " 更新成功");
        } else {
          failureNum++;
          failureMsg.append("<br/>" + failureNum + "、账号 " + user.getLoginName() + " 已存在");
        }
      } catch (Exception e) {
        failureNum++;
        String msg = "<br/>" + failureNum + "、账号 " + user.getLoginName() + " 导入失败：";
        failureMsg.append(msg + e.getMessage());
        log.error(msg, e);
      }
    }
    if (failureNum > 0) {
      failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
      throw new ServiceException(failureMsg.toString());
    } else {
      successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
    }
    return successMsg.toString();
  }

  public Long[] selectUserIdsByTenant(Long tenantId) {
    return userMapper.selectUserIdsByTenant(tenantId);
  }
}
